"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 功能
Case Name   : 多数派故障(节点正常的数量多于一半）
Create At   : 2023/04/13
Owner       : opentestcase043
Description :
        1.查询集群状态
        2.在备2查询数据库进程pid
        3.备2节点被kill数据库进程
        4.重新拉起数据库进程
        5.连接数据库做sql相关操作
        7.清理环境
Expect      :
        1.集群状态正常
        2.查询成功
        3.kill成功
        4.成功
        5.操作成功
        6.清理环境成功
History     :
"""

import os
import unittest
import time

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import macro
from yat.test import Node

LOG = Logger()
Primary_SH = CommonSH('PrimaryDbUser')


@unittest.skipIf(3 != Primary_SH.get_node_num(), '非1+2环境不执行')
class ShareStorage(unittest.TestCase):

    def setUp(self):
        LOG.info('-----this is setup-----')
        LOG.info(f'-----{os.path.basename(__file__)} start-----')
        self.con = Constant()
        self.com = Common()
        self.pri_node = Node('PrimaryDbUser')
        self.s2_sh = CommonSH('Standby2DbUser')
        self.s2_node = Node('Standby2DbUser')

    def test_share_storage(self):
        text = '-----step1:查询集群状态; expect:集群状态正常-----'
        LOG.info(text)
        status = Primary_SH.exec_cm_ctl('query', '-Cv')
        LOG.info(status)
        self.assertIn('cluster_state   : Normal', status, '执行失败:' + text)
        res = status.splitlines()[-1].split('|')[0].split('6001')[1]
        self.assertIn('P Primary Normal', res, '执行失败:' + text)

        text = '-----step2:在备2查询数据库进程pid; expect:查询成功-----'
        LOG.info(text)
        s2_pid = self.com.get_pid(self.s2_node, 'bin/gaussdb')
        self.assertNotEqual('', s2_pid, '执行失败:' + text)

        text = '-----step3:备2节点被kill数据库进程; expect:kill成功-----'
        LOG.info(text)
        cmd = f"kill -9 {s2_pid}"
        LOG.info(cmd)
        status = self.s2_node.sh(cmd).result()
        LOG.info(status)
        self.assertEqual('', status, '执行失败:' + text)

        text = '-----step4:重新拉起数据库进程; expect:成功-----'
        LOG.info(text)
        status = Primary_SH.exec_cm_ctl('start', '-n 2',
                                        f'-D {macro.DB_INSTANCE_PATH}')
        LOG.info(status)
        self.assertIn(self.con.cm_start_instance_success_msg, status,
                      '执行失败:' + text)
        time.sleep(20)
        status = Primary_SH.exec_cm_ctl('query', '-Cv')
        LOG.info(status)
        self.assertIn('cluster_state   : Normal', status, '执行失败:' + text)

        text = '-----step5:连接数据库做sql相关操作; expect:操作成功-----'
        LOG.info(text)
        cmd = f'''create table test(a int) with (segment=on);
            insert into test values(1),(0),(2),(3);
            select count(*) from test;
            drop table test;'''
        status = Primary_SH.execut_db_sql(cmd)
        LOG.info(status)
        self.assertTrue(self.con.TABLE_CREATE_SUCCESS in status
                        and self.con.INSERT_SUCCESS_MSG in status
                        and '4' in status
                        and self.con.DROP_TABLE_SUCCESS in status)

    def tearDown(self):
        text = '-----this is tearDown-----'
        LOG.info(text)
        text = '-----step7:清理环境; expect:清理环境成功-----'
        LOG.info(text)
        status1 = Primary_SH.exec_cm_ctl('start')
        status2 = Primary_SH.exec_cm_ctl('switchover', '-a')
        LOG.info(status1)
        LOG.info(status2)
        self.assertIn(self.con.cm_start_success_msg, status1,
                      '执行失败:' + text)
        self.assertIn(self.con.cm_switchover_success_msg, status2,
                      '执行失败:' + text)
        LOG.info(f'-----{os.path.basename(__file__)} end-----')
